package org.springblade.modules.bank.util;

import org.springframework.util.FileCopyUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.net.URLEncoder;
import java.util.Map;

public class DownloadUploadUtil {

	public static  void Download(Map<String,String>map, HttpServletRequest request, HttpServletResponse response){

		File file = new File(map.get("filePath"));

		//清空response中的输出流
		response.reset();
		String fileName=null;
		try{
			fileName= URLEncoder.encode(map.get("fileName"),"UTF-8");
		}catch (Exception e){
			e.printStackTrace();
		}
		//设置响应头,attachment表示以附件的形式下载，inline表示在线打开
//		if(map.get("fileType").contains("image")){
            response.setHeader("fileType",map.get("fileType"));
			response.setContentType(map.get("fileType")+";charset=UTF-8");
			response.setHeader("content-disposition","inline");
			response.setHeader("fileName",fileName);
//		}else{
//			response.setContentType("application/octet-stream;charset=UTF-8");
//			response.setHeader("content-disposition","attachment");
//			response.setHeader("fileName",fileName);
//		}
		//获取输出流对象（用于写文件）

		try(ServletOutputStream os= response.getOutputStream()){
			//下载文件,使用spring框架中的FileCopyUtils工具
//			FileCopyUtils.copy(file,os);
			FileCopyUtils.copy(new FileInputStream(file),os);
		}catch (Exception e){
			e.printStackTrace();
		}

	}

	public static String getContentType(String fileName){
		if (fileName == null) {
			fileName = "文件名为空！";
			return fileName;


		} else {
// 获取文件后缀名并转化为写，用于后续比较
			String fileType = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()).toLowerCase();
// 创建图片类型数组
			String img[] = { "bmp", "jpg", "jpeg", "png", "tiff", "gif", "pcx", "tga", "exif", "fpx", "svg", "psd",
				"cdr", "pcd", "dxf", "ufo", "eps", "ai", "raw", "wmf" };
			for (int i = 0; i < img.length; i++) {
				if (img[i].equals(fileType)) {
					return "图片";
				}
			}


// 创建文档类型数组
			String document[] = { "txt", "doc", "docx", "xls", "htm", "html", "jsp", "rtf", "wpd", "pdf", "ppt" };
			for (int i = 0; i < document.length; i++) {
				if (document[i].equals(fileType)) {
					return "文档";
				}
			}
// 创建视频类型数组
			String video[] = { "mp4", "avi", "mov", "wmv", "asf", "navi", "3gp", "mkv", "f4v", "rmvb", "webm" };
			for (int i = 0; i < video.length; i++) {
				if (video[i].equals(fileType)) {
					return "视频";
				}
			}
// 创建音乐类型数组
			String music[] = { "mp3", "wma", "wav", "mod", "ra", "cd", "md", "asf", "aac", "vqf", "ape", "mid", "ogg",
				"m4a", "vqf" };
			for (int i = 0; i < music.length; i++) {
				if (music[i].equals(fileType)) {
					return "音乐";
				}
			}


		}
		return "其他";
	}



}

